﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using TanmiaGrp.GeneralLedger.WinApp.Commands;

namespace TanmiaGrp.GeneralLedger.WinApp
{
    public static class Extensions
    {
        /// <summary>
        /// Raises <see cref="DelegateCommandBase.CanExecuteChanged"/> on the UI thread so every command invoker
        /// can requery to check if the command can execute.
        /// <remarks>Note that this will trigger the execution of <see cref="DelegateCommandBase.CanExecute"/> once for each invoker.</remarks>
        /// </summary>
        public static void RaiseCanExecuteChanged(this ICommand cmd)
        {
            if (cmd == null)
                throw new ArgumentNullException();

            if (!(cmd is DelegateCommandBase))
                throw new InvalidCastException();

            ((DelegateCommandBase)cmd).RaiseCanExecuteChanged();
        }

        /// <summary>
        /// Determines if ICollectionView.CurrentItem at first item of collection.
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        public static bool IsAtLast(this ICollectionView collection)
        {
            int count = ((ICollection)collection.SourceCollection).Count;
            return collection.CurrentPosition >= count - 1;
        }

        /// <summary>
        /// Determines if ICollectionView.CurrentItem at last item of collection.
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        public static bool IsAtFirst(this ICollectionView collection)
        {
            return collection.CurrentPosition <= 0;
        }

        public static T TryGetParent<T>(this FrameworkElement fe)
            where T : class
        {
            FrameworkElement pointer = fe;
            while (pointer != null && !(pointer is T))
                pointer = pointer.Parent as FrameworkElement;

            return pointer as T;
        }

        public static T TryGetVisualParent<T>(this DependencyObject depObject)
            where T : class
        {
            DependencyObject obj = VisualTreeHelper.GetParent(depObject);
            while (VisualTreeHelper.GetParent(obj) != null && !(obj is T))
            {
                obj = VisualTreeHelper.GetParent(obj);
            }

            // will return null if not found
            return obj as T;
        }
    }
}
